/**
 * AI智能表格管理系统 - 前端JavaScript
 * 作者：俞哲 | 浙江传媒学院 | 指导老师：栗青生
 */

class AITableManagerApp {
    constructor() {
        this.baseUrl = window.location.origin;
        this.chatMessages = document.getElementById('chatMessages');
        this.chatInput = document.getElementById('chatInput');
        this.sendBtn = document.getElementById('sendBtn');
        this.connectionDot = document.getElementById('connectionDot');
        this.connectionStatusText = document.getElementById('connectionStatusText');
        this.studentsTable = document.getElementById('studentsTableBody');
        this.tableLoading = document.getElementById('tableLoading');
        this.tableEmpty = document.getElementById('tableEmpty');

        this.isLoading = false;
        this.init();
    }

    /**
     * 初始化应用
     */
    async init() {
        console.log('正在初始化AI智能表格管理系统...');

        // 绑定事件监听器
        this.bindEventListeners();

        // 检查服务器状态
        await this.checkServerStatus();

        // 加载初始数据
        await this.loadStudentsData();
        await this.loadStatistics();

        console.log('系统初始化完成');
    }

    /**
     * 绑定事件监听器
     */
    bindEventListeners() {
        // 发送消息事件
        this.sendBtn.addEventListener('click', () => this.sendMessage());
        this.chatInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                this.sendMessage();
            }
        });

        // 清空聊天
        document.getElementById('clearChatBtn').addEventListener('click', () => this.clearChat());

        // 刷新数据
        document.getElementById('refreshDataBtn').addEventListener('click', () => {
            this.loadStudentsData();
            this.loadStatistics();
        });

        // 显示示例命令
        document.getElementById('showExamplesBtn').addEventListener('click', () => this.showExamples());

        // 显示统计信息
        document.getElementById('showStatsBtn').addEventListener('click', () => this.toggleStats());

        // 新增功能事件
        document.getElementById('addStudentBtn').addEventListener('click', () => this.showAddStudentModal());
        document.getElementById('sortByIdBtn').addEventListener('click', () => this.sortTableById());

        // 模态框事件
        document.getElementById('closeExamplesModal').addEventListener('click', () => this.hideExamples());
        document.getElementById('examplesModal').addEventListener('click', (e) => {
            if (e.target.id === 'examplesModal') {
                this.hideExamples();
            }
        });

        // 示例命令点击事件和其他点击事件
        document.addEventListener('click', (e) => {
            if (e.target.classList.contains('example-item')) {
                const command = e.target.getAttribute('data-command');
                this.chatInput.value = command;
                this.hideExamples();
                this.chatInput.focus();
            }

            // 表头排序点击事件
            if (e.target.classList.contains('sortable')) {
                const sortField = e.target.getAttribute('data-sort');
                this.sortTable(sortField);
            }

            // 操作按钮点击事件
            if (e.target.classList.contains('action-btn-edit')) {
                const studentId = e.target.getAttribute('data-id');
                this.showEditStudentModal(studentId);
            }

            if (e.target.classList.contains('action-btn-delete')) {
                const studentId = e.target.getAttribute('data-id');
                const studentName = e.target.getAttribute('data-name');
                this.showDeleteConfirmModal(studentId, studentName);
            }
        });

        // 学生表单模态框事件
        document.getElementById('closeStudentModal').addEventListener('click', () => this.hideStudentModal());
        document.getElementById('cancelStudentBtn').addEventListener('click', () => this.hideStudentModal());
        document.getElementById('studentForm').addEventListener('submit', (e) => this.handleStudentFormSubmit(e));

        // 确认删除模态框事件
        const closeConfirmModal = document.getElementById('closeConfirmModal');
        const cancelDeleteBtn = document.getElementById('cancelDeleteBtn');
        const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');

        if (closeConfirmModal) {
            closeConfirmModal.addEventListener('click', () => this.hideConfirmModal());
        } else {
            console.error('closeConfirmModal元素未找到');
        }

        if (cancelDeleteBtn) {
            cancelDeleteBtn.addEventListener('click', () => this.hideConfirmModal());
        } else {
            console.error('cancelDeleteBtn元素未找到');
        }

        if (confirmDeleteBtn) {
            confirmDeleteBtn.addEventListener('click', () => this.confirmDelete());
        } else {
            console.error('confirmDeleteBtn元素未找到');
        }

        // 模态框背景点击关闭
        const studentModal = document.getElementById('studentModal');
        const confirmModal = document.getElementById('confirmModal');

        if (studentModal) {
            studentModal.addEventListener('click', (e) => {
                if (e.target.id === 'studentModal') this.hideStudentModal();
            });
        }

        if (confirmModal) {
            confirmModal.addEventListener('click', (e) => {
                if (e.target.id === 'confirmModal') this.hideConfirmModal();
            });
        }

        // 自动聚焦输入框
        this.chatInput.focus();

        // 确保所有模态框都是隐藏的
        this.hideAllModals();
    }

    /**
     * 检查服务器状态
     */
    async checkServerStatus() {
        try {
            const response = await fetch(`${this.baseUrl}/api/health`);
            const data = await response.json();

            if (data.success) {
                this.updateStatus('connected', '已连接');
            } else {
                this.updateStatus('error', '连接错误');
            }
        } catch (error) {
            console.error('检查服务器状态失败:', error);
            this.updateStatus('error', '连接失败');
        }
    }

    /**
     * 更新状态指示器
     */
    updateStatus(status, text) {
        if (this.connectionDot && this.connectionStatusText) {
            // 更新连接状态点的颜色
            this.connectionDot.className = 'w-2 h-2 rounded-full animate-pulse';

            switch (status) {
                case 'connected':
                    this.connectionDot.classList.add('bg-green-500');
                    break;
                case 'error':
                    this.connectionDot.classList.add('bg-red-500');
                    break;
                default:
                    this.connectionDot.classList.add('bg-yellow-500');
            }

            // 更新状态文本
            this.connectionStatusText.textContent = text;
        }
    }

    /**
     * 发送消息
     */
    async sendMessage() {
        const message = this.chatInput.value.trim();

        if (!message || this.isLoading) {
            return;
        }

        // 显示用户消息
        this.addMessage(message, 'user');

        // 清空输入框并设置加载状态
        this.chatInput.value = '';
        this.setLoading(true);

        try {
            const response = await fetch(`${this.baseUrl}/api/chat`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ message })
            });

            const data = await response.json();

            if (data.success) {
                // 显示AI回复
                this.addMessage(data.response, 'ai', {
                    action: data.action,
                    result: data.result
                });

                // 如果是查询操作且有数据，刷新表格
                if (data.action === 'select' && data.result.students) {
                    await this.loadStudentsData();
                }

                // 如果是其他操作，刷新数据和统计
                if (['insert', 'update', 'delete'].includes(data.action)) {
                    await this.loadStudentsData();
                    await this.loadStatistics();
                }
            } else {
                this.addMessage(data.response || '处理请求时发生错误', 'ai');
            }

        } catch (error) {
            console.error('发送消息失败:', error);
            this.addMessage('抱歉，发送消息时发生错误，请检查网络连接并重试。', 'ai');
        } finally {
            this.setLoading(false);
        }
    }

    /**
     * 添加消息到聊天窗口
     */
    addMessage(text, type, data = null) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${type}-message`;

        const contentDiv = document.createElement('div');
        contentDiv.className = 'message-content';

        const textDiv = document.createElement('div');
        textDiv.className = 'message-text';
        textDiv.textContent = text;

        const timeDiv = document.createElement('div');
        timeDiv.className = 'message-time';
        timeDiv.textContent = new Date().toLocaleTimeString('zh-CN');

        contentDiv.appendChild(textDiv);
        contentDiv.appendChild(timeDiv);

        // 如果有数据结果，显示数据表格
        if (data && data.result && data.action === 'select' && data.result.students) {
            const dataDiv = this.createDataDisplay(data.result.students);
            contentDiv.appendChild(dataDiv);
        }

        messageDiv.appendChild(contentDiv);
        this.chatMessages.appendChild(messageDiv);

        // 滚动到底部
        this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
    }

    /**
     * 创建数据展示组件
     */
    createDataDisplay(students) {
        const dataDiv = document.createElement('div');
        dataDiv.className = 'message-data';

        const titleDiv = document.createElement('div');
        titleDiv.className = 'message-data-title';
        titleDiv.textContent = `查询结果 (${students.length} 条记录)`;

        const table = document.createElement('table');
        table.className = 'message-data-table';

        // 表头
        const thead = document.createElement('thead');
        thead.innerHTML = `
            <tr>
                <th>学号</th>
                <th>姓名</th>
                <th>年龄</th>
                <th>专业</th>
            </tr>
        `;

        // 表身
        const tbody = document.createElement('tbody');
        students.forEach(student => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${student.id}</td>
                <td>${student.name}</td>
                <td>${student.age}</td>
                <td>${student.major}</td>
            `;
            tbody.appendChild(row);
        });

        table.appendChild(thead);
        table.appendChild(tbody);

        dataDiv.appendChild(titleDiv);
        dataDiv.appendChild(table);

        return dataDiv;
    }

    /**
     * 设置加载状态
     */
    setLoading(loading) {
        this.isLoading = loading;
        this.sendBtn.disabled = loading;

        if (loading) {
            this.sendBtn.classList.add('loading');
        } else {
            this.sendBtn.classList.remove('loading');
        }
    }

    /**
     * 清空聊天记录
     */
    clearChat() {
        // 保留系统欢迎消息
        const systemMessage = this.chatMessages.querySelector('.system-message');
        this.chatMessages.innerHTML = '';
        if (systemMessage) {
            this.chatMessages.appendChild(systemMessage);
        }
    }

    /**
     * 加载学生数据
     */
    async loadStudentsData() {
        try {
            this.tableLoading.style.display = 'flex';
            this.tableEmpty.style.display = 'none';

            const response = await fetch(`${this.baseUrl}/api/students`);
            const data = await response.json();

            if (data.success && data.students) {
                this.renderStudentsTable(data.students);

                if (data.students.length === 0) {
                    this.tableEmpty.style.display = 'flex';
                }
            } else {
                this.tableEmpty.style.display = 'flex';
            }

        } catch (error) {
            console.error('加载学生数据失败:', error);
            this.tableEmpty.style.display = 'flex';
        } finally {
            this.tableLoading.style.display = 'none';
        }
    }

    /**
     * 渲染学生表格
     */
    renderStudentsTable(students) {
        this.studentsTable.innerHTML = '';

        students.forEach(student => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${student.id}</td>
                <td>${student.name}</td>
                <td>${student.age}</td>
                <td>${student.major}</td>
                <td>${new Date(student.created_at).toLocaleString('zh-CN')}</td>
                <td>
                    <div class="action-buttons">
                        <button class="action-btn action-btn-edit" data-id="${student.id}" data-name="${student.name}" data-age="${student.age}" data-major="${student.major}">
                            ✏️ 编辑
                        </button>
                        <button class="action-btn action-btn-delete" data-id="${student.id}" data-name="${student.name}">
                            🗑️ 删除
                        </button>
                    </div>
                </td>
            `;
            this.studentsTable.appendChild(row);
        });
    }

    /**
     * 加载统计信息
     */
    async loadStatistics() {
        try {
            const response = await fetch(`${this.baseUrl}/api/statistics`);
            const data = await response.json();

            if (data.success && data.statistics) {
                this.updateStatistics(data.statistics);
            }

        } catch (error) {
            console.error('加载统计信息失败:', error);
        }
    }

    /**
     * 更新统计信息
     */
    updateStatistics(stats) {
        // 更新总学生数
        document.getElementById('totalStudents').textContent = stats.totalStudents || 0;

        // 更新专业数量
        document.getElementById('totalMajors').textContent = stats.majorDistribution ? stats.majorDistribution.length : 0;

        // 计算平均年龄（需要额外的API调用，这里先显示占位符）
        document.getElementById('averageAge').textContent = '-';

        // 可以根据需要添加更多统计信息的显示
    }

    /**
     * 显示示例命令模态框
     */
    showExamples() {
        document.getElementById('examplesModal').classList.remove('hidden');
    }

    /**
     * 隐藏示例命令模态框
     */
    hideExamples() {
        document.getElementById('examplesModal').classList.add('hidden');
    }

    /**
     * 切换统计信息显示
     */
    toggleStats() {
        const statsPanel = document.getElementById('statsPanel');
        const isVisible = !statsPanel.classList.contains('hidden');

        if (isVisible) {
            statsPanel.classList.add('hidden');
        } else {
            statsPanel.classList.remove('hidden');
            this.loadStatistics(); // 重新加载统计信息
        }
    }

    // ==================== 新增功能方法 ====================

    /**
     * 显示添加学生模态框
     */
    showAddStudentModal() {
        document.getElementById('studentModalTitle').textContent = '➕ 添加学生';
        document.getElementById('editStudentId').value = '';
        document.getElementById('studentForm').reset();
        document.getElementById('studentModal').classList.remove('hidden');
        document.getElementById('studentName').focus();
    }

    /**
     * 显示编辑学生模态框
     */
    showEditStudentModal(studentId) {
        const editBtn = document.querySelector(`[data-id="${studentId}"].action-btn-edit`);
        const name = editBtn.getAttribute('data-name');
        const age = editBtn.getAttribute('data-age');
        const major = editBtn.getAttribute('data-major');

        document.getElementById('studentModalTitle').textContent = '✏️ 编辑学生';
        document.getElementById('editStudentId').value = studentId;
        document.getElementById('studentName').value = name;
        document.getElementById('studentAge').value = age;
        document.getElementById('studentMajor').value = major;
        document.getElementById('studentModal').classList.remove('hidden');
        document.getElementById('studentName').focus();
    }

    /**
     * 隐藏学生模态框
     */
    hideStudentModal() {
        document.getElementById('studentModal').classList.add('hidden');
    }

    /**
     * 处理学生表单提交
     */
    async handleStudentFormSubmit(e) {
        e.preventDefault();

        const studentId = document.getElementById('editStudentId').value;
        const name = document.getElementById('studentName').value.trim();
        const age = parseInt(document.getElementById('studentAge').value);
        const major = document.getElementById('studentMajor').value.trim();

        if (!name || !age || !major) {
            alert('请填写完整的学生信息！');
            return;
        }

        const studentData = { name, age, major };

        try {
            let response;
            if (studentId) {
                // 更新学生
                response = await this.updateStudent(studentId, studentData);
            } else {
                // 添加学生
                response = await this.addStudent(studentData);
            }

            if (response.success) {
                this.hideStudentModal();
                await this.loadStudentsData();
                await this.loadStatistics();

                // 添加成功消息到聊天
                const action = studentId ? '更新' : '添加';
                this.addMessage(`✅ 成功${action}学生：${name}`, 'system');
            } else {
                alert(`操作失败：${response.message || response.error}`);
            }
        } catch (error) {
            console.error('学生表单提交失败:', error);
            alert('操作失败，请重试');
        }
    }

    /**
     * 添加学生
     */
    async addStudent(studentData) {
        const response = await fetch(`${this.baseUrl}/api/students`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(studentData)
        });
        return await response.json();
    }

    /**
     * 更新学生
     */
    async updateStudent(studentId, studentData) {
        const response = await fetch(`${this.baseUrl}/api/students/${studentId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(studentData)
        });
        return await response.json();
    }

    /**
     * 显示删除确认模态框
     */
    showDeleteConfirmModal(studentId, studentName) {
        this.deleteStudentId = studentId;
        document.getElementById('confirmMessage').textContent =
            `确定要删除学生"${studentName}"的记录吗？此操作不可撤销。`;
        document.getElementById('confirmModal').classList.remove('hidden');
    }

    /**
     * 隐藏确认删除模态框
     */
    hideConfirmModal() {
        console.log('尝试隐藏确认删除模态框');
        const modal = document.getElementById('confirmModal');
        if (modal) {
            modal.classList.add('hidden');
            console.log('模态框已隐藏');
        } else {
            console.error('找不到确认模态框元素');
        }
        this.deleteStudentId = null;
    }

    /**
     * 确认删除学生
     */
    async confirmDelete() {
        if (!this.deleteStudentId) return;

        try {
            const response = await this.deleteStudent(this.deleteStudentId);

            if (response.success) {
                this.hideConfirmModal();
                await this.loadStudentsData();
                await this.loadStatistics();

                // 添加删除成功消息到聊天
                this.addMessage(`✅ 学生记录已删除`, 'system');
            } else {
                alert(`删除失败：${response.message || response.error}`);
            }
        } catch (error) {
            console.error('删除学生失败:', error);
            alert('删除失败，请重试');
        }
    }

    /**
     * 删除学生
     */
    async deleteStudent(studentId) {
        const response = await fetch(`${this.baseUrl}/api/students/${studentId}`, {
            method: 'DELETE'
        });
        return await response.json();
    }

    /**
     * 按学号排序表格
     */
    sortTableById() {
        this.sortTable('id');
    }

    /**
     * 表格排序功能
     */
    sortTable(field) {
        const tableBody = this.studentsTable;
        const rows = Array.from(tableBody.querySelectorAll('tr'));

        // 获取当前排序状态
        const header = document.querySelector(`[data-sort="${field}"]`);
        const currentSort = header.classList.contains('sort-asc') ? 'asc' :
                           header.classList.contains('sort-desc') ? 'desc' : 'none';

        // 清除所有排序状态
        document.querySelectorAll('.sortable').forEach(h => {
            h.classList.remove('sort-asc', 'sort-desc');
        });

        // 确定新的排序方向
        let newSort = 'asc';
        if (currentSort === 'asc') {
            newSort = 'desc';
        }

        // 设置新的排序状态
        header.classList.add(newSort === 'asc' ? 'sort-asc' : 'sort-desc');

        // 排序逻辑
        rows.sort((a, b) => {
            let aVal, bVal;

            switch (field) {
                case 'id':
                case 'age':
                    aVal = parseInt(a.cells[field === 'id' ? 0 : 2].textContent);
                    bVal = parseInt(b.cells[field === 'id' ? 0 : 2].textContent);
                    break;
                case 'name':
                    aVal = a.cells[1].textContent.toLowerCase();
                    bVal = b.cells[1].textContent.toLowerCase();
                    break;
                case 'major':
                    aVal = a.cells[3].textContent.toLowerCase();
                    bVal = b.cells[3].textContent.toLowerCase();
                    break;
                default:
                    return 0;
            }

            if (aVal < bVal) return newSort === 'asc' ? -1 : 1;
            if (aVal > bVal) return newSort === 'asc' ? 1 : -1;
            return 0;
        });

        // 重新添加排序后的行
        tableBody.innerHTML = '';
        rows.forEach(row => tableBody.appendChild(row));

        // 添加排序消息到聊天
        const sortText = newSort === 'asc' ? '升序' : '降序';
        const fieldText = {
            'id': '学号',
            'name': '姓名',
            'age': '年龄',
            'major': '专业'
        }[field];

        this.addMessage(`📊 表格已按${fieldText}${sortText}排列`, 'system');
    }

    /**
     * 隐藏所有模态框
     */
    hideAllModals() {
        console.log('隐藏所有模态框');
        const modals = ['examplesModal', 'studentModal', 'confirmModal'];
        modals.forEach(modalId => {
            const modal = document.getElementById(modalId);
            if (modal) {
                modal.classList.add('hidden');
                console.log(`${modalId} 已隐藏`);
            }
        });
    }
}

// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', () => {
    try {
        window.app = new AITableManagerApp();
        console.log('AI智能表格管理系统已启动');
    } catch (error) {
        console.error('系统启动失败:', error);
        alert('系统启动失败，请刷新页面重试');
    }
});

// 全局错误处理
window.addEventListener('error', (event) => {
    console.error('全局错误:', event.error);
});

window.addEventListener('unhandledrejection', (event) => {
    console.error('未处理的Promise拒绝:', event.reason);
});

// 导出类供其他脚本使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = AITableManagerApp;
}